/**
 * 
 */
package org.istt.web;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.istt.domain.Category;
import org.istt.domain.Exchange;
import org.istt.domain.Field;
import org.istt.domain.File;
import org.istt.domain.FileManagement;
import org.istt.domain.User;
import org.istt.domain.WorkflowProcess;
import org.istt.service.CategoryManager;
import org.istt.service.ExchangeManager;
import org.istt.service.FieldManager;
import org.istt.service.FileManager;
import org.istt.service.FileMgrManager;
import org.istt.service.UserManager;
import org.istt.service.WorkflowManager;
import org.istt.service.WorkflowProcessManager;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import com.opensymphony.xwork2.ActionContext;

/**
 * @author Huy
 * 
 */
public class FileTransAction extends BaseAction<FileManager, File, String> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 9012754123343759656L;
	private FieldManager fieldManager;
	private CategoryManager categoryManager;

	private String fromDate;
	private String fieldId;
	private String cateId;
	private List<Category> categories;
	private String status;
	//private String nextStatus;
	private List<File> files;
	private String id;
	private String groupId;
	private WorkflowProcessManager workflowProcessManager;
	private WorkflowManager workflowManager;
	private String sender;
	private FileMgrManager fileMgrManager;
	private String receiver;
	private String receiver_info;
	private String approved_comment;
	private String fileId;
	private String transferFile;
	private String reject;
	private String search;
	private String reset;
	private String searchReturnFile;
	private String userId;
	private UserManager userManager;
	private List<String> userExchanges;
	private List<String> userTransfers;
	
	private String comment;
	private ExchangeManager exchangeMgr;
	
	private File returnFile;
	@Autowired
	private FileManager fileManager;
	public FileManager getFileManager() {
		return fileManager;
	}

	public void setFileManager(FileManager fileManager) {
		this.fileManager = fileManager;
	}

	private String chkBoxReject;	
	
	
	public String getFileId() {
		return fileId;
	}

	public void setFileId(String fileId) {
		this.fileId = fileId;
	}
	
	@Autowired
	public void setWorkflowManager(WorkflowManager workflowManager) {
		this.workflowManager = workflowManager;
	}
	
	@Autowired
	public void setExchangeManager(ExchangeManager exchangeMgr) {
		this.exchangeMgr = exchangeMgr;
	}
	
	public void setComment(String comment) {
		this.comment = comment;
	}
	
	public String getComment() {
		return comment;
	}
	
	public boolean isNotEmpty(){
		if(userExchanges.get(0) != "0")
		return true;
		else return false;
	}

	public String saveExchange() {
		if (log.isDebugEnabled()) {
            log.debug("entering 'save Exchange' method");
        }
        
		File f = ((FileManager)mgr).get(id);
		for (int i = 0; i < userExchanges.size(); i++) {
			Exchange ex = new Exchange();
			ex.setFile(f);
			ex.setComment(comment);
			ex.setDate(new DateTime());
			ex.setStatus(false);
        	User approver = userManager.get(NumberUtils.toLong(userExchanges.get(i).trim()));
    		ex.setUser(approver);
    		User sender = (User)ActionContext.getContext().getSession().get(WebConstants.USER_INFO);
    		ex.setSender(sender);
            if (!comment.isEmpty())
            {
        		exchangeMgr.save(ex);
        		setSaveExchangeMessage();
        	}	        	
        }		
        		
        return SUCCESS;
	}
	
	public void setSaveExchangeMessage() {
		ActionContext.getContext().getSession()
				.put("message", getText("exchange.saved"));
	}		
	@Autowired
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
	
	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}
	
	public String getSearch() {
		return search;
	}

	public void setSearch(String search) {
		this.search = search;
	}

	public String getReject() {
		return reject;
	}

	public void setReject(String reject) {
		this.reject = reject;
	}

	public String getTransferFile() {
		return transferFile;
	}

	public void setTransferFile(String transferFile) {
		this.transferFile = transferFile;
	}

	public String execute() {
        if (transferFile != null) {
            return "transferFile";
        }
        if (reject != null) {
            return "reject";
        }
        if (reset != null) {
        	return "reset";
        }
        if ( search!= null) {
            return "search";
        }        
        
        if ( searchReturnFile!= null) {
            return "searchReturnFile";
        }        
        
        return SUCCESS;
    }
	
	
	@Override
	public String edit(){
		if(this.id!=null && !"".equals(this.id)){
			File returnFile = this.fileManager.get(id);
			if(returnFile!=null) this.returnFile = returnFile;
		}
		return SUCCESS;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(String id) {
		this.id = id;
	}


	/**
	 * @return the catList
	 */
	public List<NameValuePair> getCatList() {
		List<NameValuePair> catList = new ArrayList<NameValuePair>();
		if (!StringUtils.isEmpty(fieldId)) {
			if (log.isDebugEnabled()) {
				log.debug("fieldId is equal to " + fieldId
						+ " getting categories");
			}

			categories = categoryManager.getByFieldId(NumberUtils
					.toLong(fieldId));
			for (Category c : categories) {
				NameValuePair elm = new NameValuePair();
				elm.setName(c.getCategoryName());
				elm.setValue(c.getId() + "");
				catList.add(elm);
			}
		}

		return catList;

	}


	@Override
	protected void setSaveMessage() {
		ActionContext.getContext().getSession()
				.put("message", getText("file.transfered"));
	}


	protected void setReturnMessage() {
		ActionContext.getContext().getSession()
				.put("message", getText("file.returned"));
	}
	
	@Override
	public String getId() {
		if (!StringUtils.isEmpty(id))
			return id;
		return null;
	}

	@Override
	public String search() throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("entering 'search transfer file' method");
		}

		/*Date t = StringUtils.isEmpty(fromDate) ? null : DateUtils.parseDate(
				fromDate, new String[] { getText("date.format") });*/
		//User user_login = (User)ActionContext.getContext().getSession().get(WebConstants.USER_INFO);
		//files = ((FileManager) mgr).searchTrans(NumberUtils.toLong(fieldId), NumberUtils.toLong(cateId), NumberUtils.toLong(status), user_login.getId());

		return SUCCESS;
	}

	public String searchReturnFile() throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("entering 'search return file' method");
		}
		//User user_login = (User)ActionContext.getContext().getSession().get(WebConstants.USER_INFO);
		files = ((FileManager) mgr).searchTrans(NumberUtils.toLong(fieldId), NumberUtils.toLong(cateId), fileId, sender);

		return SUCCESS;
	}

	
	public String transferFile() {
		if (log.isDebugEnabled()) {
			log.debug("entering 'transfer file' method");
		}
		
		if ("reject".equals(chkBoxReject)) {
			//we lock this file
			FileManagement fm = fileMgrManager.getCurrentStepProcess(id);
			fm.setApprovedComment(approved_comment);
			fm.setApproveStatus(false);
			fm.setApprovedDate(DateTime.now());
			fm.setViewStatus(true);
			//Updated by THOND.2012.03.08
			fm.setReceiverRejectFile(userManager.get(NumberUtils.toLong(userTransfers.get(0).trim())));
			fileMgrManager.save(fm);
		} else if ("approve".equals(chkBoxReject)) {
			//the next step of the workflow
			FileManagement curPro = fileMgrManager.getCurrentStepProcess(id);
			
			//update the old step
			curPro.setApprovedDate(DateTime.now());
			curPro.setApproveStatus(true);
			curPro.setActiveStatus(true);
			fileMgrManager.save(curPro);
			
			WorkflowProcess curWp = curPro.getWorkflowProcess();
			Integer curPosition = curWp.getPosition();
			File f = ((FileManager) mgr).get(id);
			Integer maxPosition = workflowManager.getMaxPosition(f.getCategory().getWorkflow().getId());
			if (curPosition == maxPosition) {
				//this is the last step
				f.setDateCompleted(DateTime.now());
			} else {
				//new step
				FileManagement fm = new FileManagement();
				User sender = (User)ActionContext.getContext().getSession().get(WebConstants.USER_INFO);
				
				fm.setFile(f);
				fm.setApprover(userManager.get(NumberUtils.toLong(userTransfers.get(0).trim())));
				fm.setSender(sender);
				fm.setViewStatus(false);
				//fm.setApproveStatus(true);
				fm.setReceivedDate(DateTime.now());
				fm.setActiveStatus(false);
				//fm.setApprovedComment(approved_comment);
				
				
				WorkflowProcess nextWp = workflowProcessManager.getNextStepOfWorkflow(id, curPosition+1, null);
				fm.setWorkflowProcess(nextWp);
				
				fileMgrManager.save(fm);
			}
			
			f.setFileStatus(curWp.getFileStatus());
			((FileManager) mgr).save(f);
		}
		
		setSaveMessage();
		return SUCCESS;
	}	

	@Override
	protected void setDeleteMessage() {
		ActionContext.getContext().getSession().put("todo", null);
	}

	public String returnFile() {
		if (log.isDebugEnabled()) {
			log.debug("entering 'return file' method");
		}
		
		File newFile = ((FileManager) mgr).get(id);
		newFile.setReceiver(receiver);
		newFile.setReceiver_info(receiver_info);
		newFile.setDateGetResult(new DateTime());
		((FileManager) mgr).save(newFile);
		
		setSaveMessage();
		return SUCCESS;
	}	
	
	/**
	 * See FileTransAction-transferFile-validation.xml
	 * @return
	 */
	public boolean isNextWorkflowProcess() {
		User sender = (User)ActionContext.getContext().getSession().get(WebConstants.USER_INFO);
		List<FileManagement> fileMgnLst = fileMgrManager.searchFileMgrs(id, false, 0);
		Integer curPosition = 0;
		FileManagement fileMgn = new FileManagement();
		Boolean hasNextWorkflowProcess = false;
		for (FileManagement f : fileMgnLst) {
			if (f.getApprover().equals(sender)) {
				fileMgn=f;
				WorkflowProcess workflowProcess = fileMgn.getWorkflowProcess();
				curPosition = workflowProcess.getPosition();
				WorkflowProcess nextWorkflowProcess = new WorkflowProcess();
				nextWorkflowProcess = workflowProcessManager.getNextStepOfWorkflow(id, curPosition+1, null);
				if (nextWorkflowProcess !=null) hasNextWorkflowProcess=true;
			}
		}
		return hasNextWorkflowProcess;
	}	
	
	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public List<File> getFiles() {
		return files;
	}

	/**
	 * @return the cateId
	 */
	public String getCateId() {
		return cateId;
	}

	/**
	 * @param cateId
	 *            the cateId to set
	 */
	public void setCateId(String cateId) {
		this.cateId = cateId;
	}

	/**
	 * @return the fieldId
	 */
	public String getFieldId() {
		return fieldId;
	}

	/**
	 * @param fieldId
	 *            the fieldId to set
	 */
	public void setFieldId(String fieldId) {
		this.fieldId = fieldId;
	}

	/**
	 * @return the fromDate
	 */
	public String getFromDate() {
		return fromDate;
	}

	/**
	 * @param fromDate
	 *            the fromDate to set
	 */
	public void setFromDate(String fromDate) {
		this.fromDate = fromDate;
	}


	/**
	 * @return the fields
	 */
	public List<Field> getFields() {
		return fieldManager.getList();
	}

	/**
	 * @param fieldManager
	 *            the fieldManager to set
	 */
	public void setFieldManager(FieldManager fieldManager) {
		this.fieldManager = fieldManager;
	}

	/**
	 * @param categoryManager
	 *            the categoryManager to set
	 */
	public void setCategoryManager(CategoryManager categoryManager) {
		this.categoryManager = categoryManager;
	}
	

	public void setGroupId(String groupId) {
		this.groupId = groupId;
	}

	public String getGroupId() {
		return groupId;
	}

	public void setWorkflowProcessManager(WorkflowProcessManager workflowProcessManager) {
		this.workflowProcessManager = workflowProcessManager;
	}

	public void setFileMgrManager(FileMgrManager fileMgrManager) {
		this.fileMgrManager = fileMgrManager;
	}

	public void setSender(String sender) {
		this.sender = sender;
	}

	public String getSender() {
		return sender;
	}


	public void setReceiver(String receiver) {
		this.receiver = receiver;
	}

	public String getReceiver() {
		return receiver;
	}

	public void setReceiver_info(String receiver_info) {
		this.receiver_info = receiver_info;
	}

	public String getReceiver_info() {
		return receiver_info;
	}

	public void setApproved_comment(String approved_comment) {
		this.approved_comment = approved_comment;
	}

	public String getApproved_comment() {
		return approved_comment;
	}
	
	public void setSearchReturnFile(String searchReturnFile) {
		this.searchReturnFile = searchReturnFile;
	}

	public String getSearchReturnFile() {
		return searchReturnFile;
	}

	public List<String> getUserExchanges() {
		return userExchanges;
	}

	public void setUserExchanges(List<String> userExchanges) {
		this.userExchanges = userExchanges;
	}

	public List<String> getUserTransfers() {
		return userTransfers;
	}

	public void setUserTransfers(List<String> userTransfers) {
		this.userTransfers = userTransfers;
	}

	public void setChkBoxReject(String chkBoxReject) {
		this.chkBoxReject = chkBoxReject;
	}

	public String getChkBoxReject() {
		return chkBoxReject;
	}
	
	/**
	 * See FileTransAction-transferFile-validation.xml
	 * @return
	 */
	public boolean isApproveCommentValid() {
		boolean isValid = true;
		
		if ("reject".equals(chkBoxReject) && 
					StringUtils.isEmpty(approved_comment)) {
			isValid = false;
		}
		return isValid;
	}
	
	public String getReceivedDate() {
		DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
		Date date = new Date();
		String receivedDate =dateFormat.format(date);		
		return receivedDate;
	}	
	
	/**
	 * See FileTransAction-transferFile-validation.xml
	 * @return
	 */
	public boolean isUserRequired() {
		boolean isValid = true;
		//Updated by Thond.2012.03.06
		if (!CollectionUtils.isEmpty(userTransfers) && userTransfers.get(0).equals("0")){
			isValid = false;
		}
		return isValid;
	}

	//Created by Thond.2012.03.06
	public boolean isValidUser() {
		boolean isValid = true;
		if ("reject".equals(chkBoxReject)
				&& !CollectionUtils.isEmpty(userTransfers) && userTransfers.get(0).equals("0")){
			isValid = false;
		}
		return isValid;
	}

	public void setReturnFile(File returnFile) {
		this.returnFile = returnFile;
	}

	public File getReturnFile() {
		return returnFile;
	}

	public void setReset(String reset) {
		this.reset = reset;
	}

	public String getReset() {
		return reset;
	}
}
